<template>
    <div class="app-container">
        <!-- 顶部搜索栏 -->
        <el-card>
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="模板名称">
                        <el-input v-model="searchForm.templateName" placeholder="模板名称" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="厂商名称">
                        <el-input v-model="searchForm.vendor" placeholder="厂商名称" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="模板型号">
                        <el-input v-model="searchForm.model" placeholder="模板型号" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="是否推送">
                        <el-select v-model="searchForm.pushEnabled" placeholder="是否推送" clearable>
                            <el-option label="不推送" value="0"></el-option>
                            <el-option label="推送" value="1"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20" style="margin-top: 20px;">
                <el-col :span="6">
                    <el-form-item label="是否启用">
                        <el-select v-model="searchForm.enabled" placeholder="是否启用" clearable>
                            <el-option label="禁用" value="0"></el-option>
                            <el-option label="启用" value="1"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="14" class="text-left">
                    <el-button type="primary" @click="handleSearch" icon="search">搜索</el-button>
                    <el-button @click="handleReset">
                        <el-icon>
                            <Refresh />
                        </el-icon>重置
                    </el-button>
                </el-col>
            </el-row>
        </el-card>

        <!-- 模板表格 -->
        <el-card class="mt-1">
            <el-button type="primary" @click="showCreateDialog">
                <el-icon>
                    <Plus />
                </el-icon>
                新增模板
            </el-button>

            <el-table v-loading="loading" :data="tableData" class="mt-2" border
                @selection-change="handleSelectionChange">
                <el-table-column type="index" label="序号" width="60" align="center" />
                <el-table-column prop="templateName" label="模板名称" align="center" />
                <el-table-column prop="vendor" label="厂商名称" align="center" />
                <el-table-column prop="model" label="设备型号" align="center" />
                <el-table-column prop="pushEnabled" label="是否推送" align="center">
                    <template #default="{ row }">{{ row.pushEnabled === 1 ? '是' : '否' }}</template>
                </el-table-column>
                <el-table-column prop="enabled" label="是否启用" align="center">
                    <template #default="{ row }">{{ row.enabled === 1 ? '启用' : '禁用' }}</template>
                </el-table-column>
                <el-table-column prop="createdAt" label="创建时间" align="center" width="180" />
                <el-table-column label="操作" width="220" align="center" fixed="right">
                    <template #default="{ row }">
                        <el-button type="text" @click="showDetailDialog(row.id)">详情</el-button>
                        <el-button type="text" @click="showEditDialog(row.id)">编辑</el-button>
                        <!-- <el-button type="text" @click="handleDelete(row.id)" style="color: #F56C6C">删除</el-button> -->
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination class="mt-2" v-model:current-page="queryParams.pageNum"
                v-model:page-size="queryParams.pageSize" :page-sizes="[10, 20, 30, 50]"
                layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </el-card>

        <!-- 新增/编辑对话框 -->
        <el-dialog v-model="dialogVisible" :title="`${isEditMode ? '编辑' : '新增'}行业设备模板`" width="600px"
            @closed="handleDialogClosed">
            <el-form :model="formData" :rules="rules" ref="formRef" label-width="120px">
                <el-form-item label="模板名称" prop="templateName">
                    <el-input v-model="formData.templateName" placeholder="请输入模板名称" />
                </el-form-item>
                <el-form-item label="厂家名称" prop="vendor">
                    <el-input v-model="formData.vendor" placeholder="请输入厂家名称" />
                </el-form-item>
                <el-form-item label="设备型号" prop="model">
                    <el-input v-model="formData.model" placeholder="请输入设备型号" />
                </el-form-item>
                <el-form-item label="连接配置" prop="connectionSpec">
                    <el-input v-model="formData.connectionSpec" placeholder="请输入连接配置" />
                </el-form-item>
                <el-form-item label="上行解析配置" prop="parseSpec">
                    <el-input v-model="formData.parseSpec" placeholder="请输入上行解析配置" />
                </el-form-item>
                <el-form-item label="下行命令定义" prop="commandSpec">
                    <el-input v-model="formData.commandSpec" placeholder="请输入下行命令定义" />
                </el-form-item>
                <el-form-item label="启用数据转推" prop="pushEnabled">
                    <el-select v-model="formData.pushEnabled" placeholder="请选择是否推送">
                        <el-option label="启用" value="0"></el-option>
                        <el-option label="不启用" value="1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="转推配置" prop="pushSpec">
                    <el-input v-model="formData.pushSpec" placeholder="请输入转推配置" />
                </el-form-item>
                <el-form-item label="心跳间隔(秒)" prop="heartbeatSec">
                    <el-input v-model.number="formData.heartbeatSec" placeholder="请输入心跳间隔" type="number" min="1" />
                </el-form-item>
                <el-form-item label="接收超时(秒)" prop="recvTimeoutSec">
                    <el-input v-model.number="formData.recvTimeoutSec" placeholder="请输入接收超时" type="number" min="1" />
                </el-form-item>
                <el-form-item label="失败重试次数" prop="retryLimit">
                    <el-input v-model.number="formData.retryLimit" placeholder="请输入重试次数" type="number" min="0" />
                </el-form-item>
                <el-form-item label="是否启用" prop="enabled">
                    <el-select v-model="formData.enabled" placeholder="请选择是否启用">
                        <el-option label="禁用" value="0"></el-option>
                        <el-option label="启用" value="1"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit">确定</el-button>
            </template>
        </el-dialog>

        <!-- 详情对话框 -->
        <el-dialog v-model="detailDialogVisible" title="模板详情" width="600px">
            <el-descriptions :column="2" border>
                <el-descriptions-item label="模板ID">{{ detailData.id }}</el-descriptions-item>
                <el-descriptions-item label="模板名称">{{ detailData.templateName }}</el-descriptions-item>
                <el-descriptions-item label="厂家/厂商名称">{{ detailData.vendor }}</el-descriptions-item>
                <el-descriptions-item label="设备型号/系列">{{ detailData.model }}</el-descriptions-item>
                <el-descriptions-item label="是否启用模板">{{ detailData.enabled === 1 ? '启用' : '禁用' }}</el-descriptions-item>
                <el-descriptions-item label="连接配置">{{ detailData.connectionSpec }}</el-descriptions-item>
                <el-descriptions-item label="上行解析配置">{{ detailData.parseSpec }}</el-descriptions-item>
                <el-descriptions-item label="下行命令定义">{{ detailData.commandSpec }}</el-descriptions-item>
                <el-descriptions-item label="是否启用数据转推">{{ detailData.pushEnabled === 1 ? '是' : '否'
                    }}</el-descriptions-item>
                <el-descriptions-item label="转推配置">{{ detailData.pushSpec }}</el-descriptions-item>
                <el-descriptions-item label="心跳/保活间隔(秒)">{{ detailData.heartbeatSec }}</el-descriptions-item>
                <el-descriptions-item label="接收超时(秒)">{{ detailData.recvTimeoutSec }}</el-descriptions-item>
                <el-descriptions-item label="失败重试次数上限">{{ detailData.retryLimit }}</el-descriptions-item>
                <el-descriptions-item label="创建时间">{{ detailData.createdAt }}</el-descriptions-item>
                <el-descriptions-item label="更新时间">{{ detailData.updatedAt }}</el-descriptions-item>
            </el-descriptions>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Edit, Delete, Refresh } from '@element-plus/icons-vue'
import DictTag from '@/components/DictTag'
import * as api from '@/api/park/device/businessFacilitiesTemplate'

// 查询参数
const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
})

// 搜索表单
const searchForm = reactive({
    templateName: undefined,
    vendor: undefined,
    model: undefined,
    pushEnabled: undefined,
    enabled: undefined
})
// 表格数据
const tableData = ref([])
const total = ref(0)
const loading = ref(false)
const selectedIds = ref([])

// 表单数据
const formData = ref({
    id: undefined,
    templateName: '',
    vendor: '',
    model: '',
    enabled: '',
    connectionSpec: '',
    parseSpec: '',
    commandSpec: '',
    pushEnabled: '',
    pushSpec: '',
    heartbeatSec: '',
    recvTimeoutSec: '',
    retryLimit: ''
})

// 表单验证规则
const rules = reactive({
    templateName: [
        { required: true, message: '请输入模板名称', trigger: 'blur' }
    ],
    vendor: [
        { required: true, message: '请输入厂家/品牌', trigger: 'blur' }
    ],
    model: [
        { required: true, message: '请输入型号/系列', trigger: 'blur' }
    ],
    connectionSpec: [
        { required: true, message: '请输入连接配置（JSON：协议/地址/端口/鉴权/主题/轮询/串口等）', trigger: 'blur' }
    ],
    parseSpec: [
        { required: true, message: '请输入上行解析配置', trigger: 'blur' }
    ],
})

// 设备类型下拉选项
const deviceTypeOptions = ref([])

// 对话框控制
const dialogVisible = ref(false)
const isEditMode = ref(false)
const formRef = ref(null)
const detailDialogVisible = ref(false)
const detailData = ref({})

// 初始化数据
onMounted(() => {
    getList()
    getDeviceTypeOptions()
})

// 获取设备类型下拉选项
const getDeviceTypeOptions = async () => {
    try {
        const res = await api.getBusinessTypeList()
        deviceTypeOptions.value = res.data
    } catch (error) {
        console.error('获取设备类型下拉选项失败:', error)
        ElMessage.error('获取设备类型下拉选项失败')
    }
}

// 获取列表数据
const getList = async () => {
    try {
        loading.value = true
        const params = {
            ...queryParams,
            ...searchForm
        }
        const res = await api.getTemplateList(params)
        tableData.value = res.rows
        total.value = res.total
    } catch (error) {
        console.error('获取列表失败:', error)
        ElMessage.error('获取列表失败')
    } finally {
        loading.value = false
    }
}

// 搜索
const handleSearch = () => {
    queryParams.pageNum = 1
    getList()
}

// 重置
const handleReset = () => {
    Object.assign(searchForm, {
        parameter: ''
    })
    handleSearch()
}

// 分页大小变化
const handleSizeChange = (val) => {
    queryParams.pageSize = val
    getList()
}

// 当前页变化
const handleCurrentChange = (val) => {
    queryParams.pageNum = val
    getList()
}

// 选择变化
const handleSelectionChange = (selection) => {
    selectedIds.value = selection.map(item => item.id)
}

// 显示新增对话框
const showCreateDialog = () => {
    isEditMode.value = false
    dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = async (id) => {
    try {
        loading.value = true
        const res = await api.getTemplateDetail(id)
        // Object.assign(formData, res.data)
        formData.value = res.data
        isEditMode.value = true
        dialogVisible.value = true
    } catch (error) {
        console.error('获取模板详情失败:', error)
        ElMessage.error('获取模板详情失败')
    } finally {
        loading.value = false
    }
}

const resetFormData = () => {
    formData.value = {
        id: undefined,
        templateName: '',
        vendor: '',
        model: '',
        enabled: '',
        connectionSpec: '',
        parseSpec: '',
        commandSpec: '',
        pushEnabled: '',
        pushSpec: '',
        heartbeatSec: '',
        recvTimeoutSec: '',
        retryLimit: ''
    }
}
// 对话框关闭
const handleDialogClosed = () => {
    formRef.value?.resetFields()
    resetFormData()
}

// 提交表单
const handleSubmit = () => {
    formRef.value.validate(async (valid) => {
        if (!valid) return

        try {
            if (isEditMode.value) {
                await api.updateTemplate(formData.value)
                ElMessage.success('修改成功')
            } else {
                await api.addTemplate(formData.value)
                ElMessage.success('新增成功')
            }
            dialogVisible.value = false
            getList()
        } catch (error) {
            console.error('提交失败:', error)
            ElMessage.error('提交失败')
        }
    })
}

// 显示详情对话框
const showDetailDialog = async (id) => {
    try {
        loading.value = true
        const res = await api.getTemplateDetail(id)
        detailData.value = res.data
        detailDialogVisible.value = true
    } catch (error) {
        console.error('获取详情失败:', error)
        ElMessage.error('获取详情失败')
    } finally {
        loading.value = false
    }
}

// 删除
const handleDelete = (id) => {
    ElMessageBox.confirm('确定要删除该模板吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            await api.deleteTemplate(id)
            ElMessage.success('删除成功')
            getList()
        } catch (error) {
            console.error('删除失败:', error)
            ElMessage.error('删除失败')
        }
    }).catch(() => {
        // 取消删除
    })
}
</script>

<style scoped>
.app-container {
    padding: 20px;
}

.text-right {
    text-align: right;
}

.mt-2 {
    margin-top: 20px;
}

.el-button+.el-button {
    margin-left: 8px;
}
</style>